define([
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/dialog",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
    "Date", "DateCN", "css!DateCss",
    "EasyUI", "EasyUI-lang"
], function (Util, Tool, Dialog, SelectOrg, SearchBlock) {

    var sysPath = getServer() + "/static/app/fxpg/fxPicture";

    var fxPictureFormHtml = sysPath + "/views/fxPictureForm.html";
    var getFxPictureController = function () {
        return getServer() + "/fx/fxPictures";
    };

    /**
     * 页面初始化
     */
    var init = function () {
        initSearchBlock();
        queryBtnBind();
        initcreateProvince();
        createFxPictureGrid();
    };


    var initSearchBlock = function () {
        SearchBlock.init("searchBlock");
    };
    /**
     * 查询参数
     */
    var queryBtnBind = function () {
        $("#btnSearch").click(function () {
            createFxPictureGrid();
        });
        // 参数重置
        $("#btnReset").click(function () {
            $("#pictureNameCondition").val("");
            $("#pictureDescriptionCondition").val("");
            $("#createUser").val("");
            $("#type").val("");
            // 地区
            $("#provinceSelect").val("");
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
            $("#citySelect").append(html);
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
        });
    };

    /**
     * 搜索栏省市区
     */
    var initcreateProvince = function () {
        var html = "";
        $("#citySelect").append(html);
        $("#areaSelect").append(html);
        $.ajax({
            url: getServer() + "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#provinceSelect").append(html);
            }
        });
        $("#provinceSelect").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
            $("#citySelect").append(html);
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#citySelect").append(html);
                }
            });
        });
        $("#citySelect").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#areaSelect").append(html);
                }
            });
        });
    }
    // 添加表单省市区
    var initcreateProvinceForm = function () {
        var html = "";
        $("#city").append(html);
        $("#area").append(html);
        $.ajax({
            url: getServer() + "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#province").append(html);
            }
        });
        $("#province").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#city option").remove();
            $("#city").append(html);
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#city").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#city").append(html);
                }
            });
        });
        $("#city").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#area").append(html);
                }
            });
        });
    }

    // 编辑表单省市区
    var editProvince = function (Province, City, Area) {
        debugger;
        var html = "";
        $("#city").append(html);
        $("#area").append(html);
        $.ajax({
            url: getServer() + "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    if (item.divisionName == Province) {
                        debugger;
                        var divisionId = item.divisionId;
                        var htmlCity = '';
                        if (Province == "北京市" || Province == "天津市" || Province == "上海市" || Province == "重庆市") {
                            $("#city").append("<option value='" + Province + "' exid='" + divisionId + "'>" + Province + "</option>");
                            $('#city').val(City);
                            var htmlArea = '';
                            $.ajax({
                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    $.each(data, function (idx, item) {
                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#area").append(htmlArea);
                                    $('#area').val(Area);
                                }
                            });

                        } else {
                            $.ajax({
                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    debugger;
                                    $.each(data, function (idx, item) {
                                        if (item.divisionName == City) {
                                            var divisionId = item.divisionId;
                                            var htmlArea = '';
                                            $.ajax({
                                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                                contentType: "application/json",
                                                type: "get",
                                                success: function (data) {
                                                    $.each(data, function (idx, item) {
                                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                                    });
                                                    $("#area").append(htmlArea);
                                                    $('#area').val(Area);
                                                }
                                            });
                                        }
                                        htmlCity += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#city").append(htmlCity);
                                    $('#city').val(City);
                                }
                            });
                        }
                    }
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#province").append(html);
                $('#province').val(Province);
            }
        });
        $("#province").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#city option").remove();
            $("#city").append(html);
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#city").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#city").append(html);
                }
            });
        });
        $("#city").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#area").append(html);
                }
            });
        });
    }

    /**
     * 查询结果列表
     */
    var createFxPictureGrid = function () {
        $("#fxPictureGrid").datagrid({
            url: getFxPictureController() + "/queryFxPictures",
            method: "GET",
            fitColumns: true,
            autoRowHeight: false,
            columns: [[
                {field: "ck", checkbox: true},
                {
                    field: 'pictureName',
                    title: '图件名称',
                    width: '18%',
                    align: 'center',
                    formatter: function (value, rowData, rowIndex) {
                        return '<a href="#" onclick="_editFxPicture(\'' + rowData.id + '\');"> ' + rowData.pictureName + ' </a> '
                    }
                },
                {
                    field: 'pictureDescription',
                    title: '图件描述',
                    width: '18%',
                    align: 'center',
                },
                {
                    field: 'type',
                    title: '结果分类',
                    width: '12%',
                    align: 'center',
                },
                {
                    field: 'province',
                    title: '省',
                    width: '12%',
                    align: 'center',
                },
                {
                    field: 'city',
                    title: '市',
                    width: '10%',
                    align: 'center',
                },
                {
                    field: 'area',
                    title: '区（县）',
                    width: '10%',
                    align: 'center',
                },
                {
                    field: 'createUser',
                    title: '创建人',
                    width: '10%',
                    align: 'center',
                },
                {
                    field: 'createTime',
                    title: '上传时间',
                    width: '10%',
                    align: 'center',
                },
            ]],
            toolbar: [{
                iconCls: 'fa fa-plus-circle',
                text: "添加",
                handler: function () {
                    addFxPicture();
                }
            }, {
                iconCls: 'fa fa-plus-circle',
                text: "模板",
                handler: function () {
                    downloadTemplate();
                }
            }, {
                iconCls: 'fa fa-upload',
                text: "文件批量导入",
                handler: function () {
                    upload();
                }
            }, {
                iconCls: 'fa fa-upload',
                text: "导入",
                handler: function () {
                    importForm();
                }
            }, {
                iconCls: 'fa fa-trash-o',
                text: "删除",
                handler: function () {
                    deleteFxPicture();
                }
            }],
            queryParams: {
                province: $("#provinceSelect").val(),
                city: $("#citySelect").val(),
                area: $("#areaSelect").val(),
                pictureName: $("#pictureNameCondition").val(),
                pictureDescription: $("#pictureDescriptionCondition").val(),
                type: $("#type").val(),
                createUser: $("#createUser").val(),
            },
            pagination: true,
            pageSize: 10
        });
    };
    /**
     * 表单校验
     */
    var formValidator = function () {
        $("#fxPictureForm").validate({
            rules: {
                pictureName: {
                    required: true,
                },
                pictureDescription: {
                    required: true,
                },
                type: {
                    required: true,
                },
                province: {
                    required: true,
                }
            },
            messages: {
                pictureName: {
                    required: "图件名称不允许为空!",
                },
                pictureDescription: {
                    required: "图件描述不允许为空!",
                },
                type: {
                    required: "结果类型不能为空！",
                },
                province: {
                    required: "省份不能为空！",
                }
            }
        });
    };
    /**
     * 获取一条信息
     */
    var getFxPicture = function (id) {
        $.ajax({
            url: getFxPictureController() + "/" + id,
            type: "get",
            success: function (data) {
                editProvince(data.province, data.city, data.area);
                Tool.deserialize("fxPictureForm", data);
                viewFileUpload(data.attachId);
            }
        });
    };
    /**
     * 添加
     */
    var addFxPicture = function () {
        var slidebar = Util.slidebar({
            url: fxPictureFormHtml,
            width: "580px",
            cache: false,
            close: true,
            afterLoad: function () {
                // 添加初始化省市区
                initcreateProvinceForm();
                formValidator();
                // 附件
                fileUpload();
                $("#saveBtn").on("click", function () {
                    if ($("#fxPictureForm").valid()) {
                        var data = Tool.serialize("fxPictureForm");
                        $.ajax({
                            url: getFxPictureController(),
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "post",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createFxPictureGrid();
                            }
                        });
                    }
                });
            }
        });
    };

    // 下载模板
    var downloadTemplate = function () {
        window.location.href = getServer() + "/excel/图件数据模板.xlsx";
    };

    // 文件批量导入
    window.upload = function () {
        debugger;
        var buttons = [];
        buttons.push({
            name: '确定',
            callback: function () {
                //点击确定
                debugger;
                dialog.hide();
            }
        });
        var dialog = Dialog({
            id: "viewTeamDialog",
            cache: false,
            title: '上传附件', //dialog标题
            width: "900px",
            height: "350px",
            body: '<div id="TeamGrid">' +
                '<div class="col-md-12 form-horizontal">' +
                '<div class="form-group">' +
                '<label for="detailFile" class="col-md-2 control-label">文档:</label>' +
                '<div class="col-md-10" id="multiFileUpload">' +
                '<input id="detailFile" type="hidden" name="detailFile" class="form-control"  />' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>',
            buttons: buttons,
            afterOpen: function () {
                require(['UtilDir/fileupload/multiFileUpload'], function (MFU) {
                    var attachId = "";
                    var settings = {
                        placeAt: "multiFileUpload",
                        allowMC: false,
                        fileSizeLimit: 200 * 1024 * 1024,
                        onUploadSuccess: function (file) {
                            attachId += file.attachId + ",";
                            $("#detailFile").val(attachId.substr(0, attachId.length - 1));
                        },
                        onDeleteSavedFile: function (file) {
                            //console.log(file)
                        }
                    };
                    MFU.init(settings);
                });

            }
        });
        dialog.show();
    };

    // 导入
    var importForm = function () {
        // 模板下载
        $("#uploadModal").modal();
        $("#uploadModal").on("shown.bs.modal", function () {
            var url = getServer() + "/excel/图件数据模板.xlsx";
            $("#downloadZwExcelTemplate").attr("href", url);
        });

        $('#uploadButton').off("click");
        $("#uploadButton").on("click", function () {
            var uploadinput = document.getElementById("uploadFile");
            if (uploadinput.value == "") {
                Util.alert("上传前请先选择文件!");
                return;
            }
            var formData = new FormData();
            formData.append("file", uploadinput.files[0]);
            $.ajax({
                url: getFxPictureController() + "/import",
                data: formData,
                processData: false, //因为data值是FormData对象，不需要对数据做处理。
                contentType: false,
                type: "POST",
                success: function (data) {
                    $('#uploadModal').modal('hide');
                    uploadinput.value = null;
                    createFxPictureGrid();
                    Util.alert(data);
                }
            });
        });
    };

    /**
     * 编辑
     */
    window._editFxPicture = function (fxPictureId) {
        var slidebar = Util.slidebar({
            url: fxPictureFormHtml,
            width: "580px",
            cache: false,
            close: true,
            afterLoad: function () {
                formValidator();
                getFxPicture(fxPictureId);
                $("#saveBtn").on("click", function () {
                    if ($("#fxPictureForm").valid()) {
                        var data = Tool.serialize("fxPictureForm");
                        console.log(data);
                        $.ajax({
                            url: getFxPictureController(),
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "put",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createFxPictureGrid();
                            }
                        });
                    }
                });
            }
        });
    };
    /**
     * 删除
     */
    var deleteFxPicture = function () {
        var rows = $("#fxPictureGrid").datagrid("getSelections");
        if (rows == null || rows.length == 0) {
            Util.alert("请选择一行数据!");
            return;
        }
        Util.confirm("是否要删除选中的数据?", function () {
            var ids = "";
            $.each(rows, function (i, row) {
                ids += row.id + ",";

            });
            ids = ids.substr(0, ids.length - 1);
            $.ajax({
                url: getFxPictureController(),
                data: {
                    ids: ids
                },
                type: "delete",
                success: function (data) {
                    createFxPictureGrid();
                }
            });
        }, function () {
            return;
        });

    };

    //------------------------------------附件接口---------------------------------------//

    /**
     * 上传附件
     */
    var fileUpload = function () {
        require(['UtilDir/fileupload/multiFileUpload'], function (MFU) {
            var attachId = "";
            var settings = {
                placeAt: "multiFileUpload",
                allowMC: false,
                fileSizeLimit: 200 * 1024 * 1024,
                /*
	            1.0.2版本新增
	            extendColumn:[
	                {name:"文件分类",filed:"category",format:function(file){return file.name}},
	                {name:"备注",filed:"remark",format:function(file){return '机密'}}
	            ],*/
                //data:["5a50d697c0af806aa01e06120d04f977","6c01e4492f264befab4c0532811f8dff"],
                onUploadSuccess: function (file) {
                    attachId += file.attachId + ",";
                    $("#attachId").val(attachId.substr(0, attachId.length - 1));
                },
                onDeleteSavedFile: function (file) {
                    //console.log(file)
                }
            };
            MFU.init(settings);
        });
    };

    /**
     * 查看文件
     * @param fileData
     */
    var viewFileUpload = function (fileData) {
        require(['UtilDir/fileupload/multiFileUpload'], function (MFU) {
            var attachIdData = "";
            var attachId = "";
            var fileArray = "";
            if (fileData.length != 0) {
                attachIdData = fileData.split(',');
                fileArray = fileData.split(',');
            }
            var settings = {
                placeAt: "multiFileUpload",
                allowMC: false,
                fileSizeLimit: 200 * 1024 * 1024,
                /*
	            1.0.2版本新增
	            extendColumn:[
	                {name:"文件分类",filed:"category",format:function(file){return file.name}},
	                {name:"备注",filed:"remark",format:function(file){return '机密'}}
	            ],*/
                data: attachIdData,
                onUploadSuccess: function (file) {
                    attachId += file.attachId + ",";
                    if (fileData.length == 0) {
                        $("#attachId").val(attachId.substr(0, attachId.length - 1));
                    } else {
                        $("#attachId").val(fileData + "," + attachId.substr(0, attachId.length - 1));
                    }

                },
                onDeleteSavedFile: function (file) {
                    var index = fileArray.indexOf(file.attachId);
                    fileArray.splice(index, 1);
                    $("#attachId").val(fileArray.toString());
                }
            };
            MFU.init(settings);
        });
    };


    return {
        init: init
    };
});
